package com.huluobo.day11_im.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.huluobo.day11_im.R;
import com.huluobo.day11_im.activity.MainActivity;
import com.huluobo.day11_im.pay.PayResult;
import com.huluobo.day11_im.pay.util.OrderInfoUtil2_0;
import com.hyphenate.easeui.modules.chat.EaseChatFragment;
import com.hyphenate.easeui.modules.chat.interfaces.IChatExtendMenu;

import java.util.Map;

import pub.devrel.easypermissions.EasyPermissions;

public class ChatFragment extends EaseChatFragment {
    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "2021000122688185";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";
    /**
     * pkcs8 格式的商户私钥。
     * <p>
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     * <p>
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE =
            "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCWcpkNcLzN8DR76VpObD1erp6H42npymuKiYAMYopRBiQs" +
                    "/ONzX5xEFHLX7PgtrAq3SFK/rwqkq9t1syT3SridvzyEmvUbpTRlZsT3vI6bbQA" +
                    "+vvZpROFWHDtfHE46yQCQ6TN1b4An53HIbbH8B+1Kj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vECgYEAmImOd8eTJuYha+hfBe/dOjmUfbTXO92w9URbLwlzp5jch3Cpoc4T6DElrO7G8D4jvPp2iM5sI+c6TViZv5llgzKmiCT6zAM4LKQPh9jw1+l0txRaGTWcbLelVrMGjiCxJINFtc9xuXGu/ie5kPIkrui5HugngNJvS1eL5b3T7o0CgYBvvYXTgwSkc8BSmEUVpWIlHhg90MU97UPjxc9KN6mOCNbCNLNEmnb94U2rRwrbSXsFSVAhzXT4tDfW0aSdBpglmXbUvMgOuGswUcPRFwBUjDawygeTcX10rjQxnp47eVFIPkzFLEaAOZnWyNGl79DX+a9IF7UJ2mF057oCEkUPWA==";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked") PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付成功");
                        Toast.makeText(getContext(), "支付成功", Toast.LENGTH_SHORT).show();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付失败" + payResult);
                        Toast.makeText(getContext(), "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };

    /**
     * 支付宝支付业务示例
     */
    public void pay() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @Override
    public void initView() {
        super.initView();
        IChatExtendMenu chatExtendMenu = chatLayout.getChatInputMenu().getChatExtendMenu();
        chatExtendMenu.registerMenuItem("红包", R.drawable.pay, 333);
    }

    @Override
    public void onChatExtendMenuItemClick(View view, int itemId) {
        if (itemId == 333) {
            pay();
        }
        super.onChatExtendMenuItemClick(view, itemId);
    }

    /**
     * 地图定位结果处理
     *
     * @param data
     */
    protected void onActivityResultForMapLocation(@Nullable Intent data) {
        if (data != null) {
            double latitude = data.getDoubleExtra("latitude", 0);
            double longitude = data.getDoubleExtra("longitude", 0);
            String locationAddress = data.getStringExtra("address");
            String buildingName = data.getStringExtra("buildingName");
            if (locationAddress != null && !locationAddress.equals("")) {
                chatLayout.sendLocationMessage(latitude, longitude, locationAddress, buildingName);
            } else {
                chatLayout.sendLocationMessage(latitude, longitude, "未知地点", "未知地址");

            }
//                if(listener != null) {
//                    listener.onChatError(-1, getResources().getString(R.string.unable_to_get_loaction));
//                }
//            }
        }
    }
}